// TemplateSwiper.tsx
import React, { useEffect, useState } from 'react';
import './TemplateSwiper.scss';
import { RightOutlined, LeftOutlined, StarOutlined, EyeOutlined, EllipsisOutlined, CrownOutlined, ShareAltOutlined, CalendarOutlined } from '@ant-design/icons';
import { Button } from 'antd';
import axios from 'axios';
import search from '../../../public/loginImg/search.jpg'
import search2 from '../../../public/loginImg/search2.jpg'
import { useNavigate } from 'react-router-dom';

//最近打开的函数
// 在组件顶部添加记录最近打开的函数
const recordRecentAccess = (item: SwiperItem, title: string) => {
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || {});
  if (userInfo && userInfo.id) {
    const userId = userInfo.id;
    const recentItem = {
      id: item.id,
      img: item.img,
      title: item.popupTitle || `${title} ${item.id}`,
      time: new Date().toISOString(),
      link: item.link || '/Createdesign' // 实际项目中应使用正确链接
    };
    
    // 获取现有记录
    const recentKey = `recentItems_${userId}`;
    const recentItems = JSON.parse(localStorage.getItem(recentKey) || []);
    
    // 移除重复项
    const newItems = [
      recentItem,
      ...recentItems.filter((i: any) => i.id !== item.id)
    ].slice(0, 20); // 最多保留20条
    
    localStorage.setItem(recentKey, JSON.stringify(newItems));
  }
};







interface SwiperItem {
  id: number;
  img: string;
  popupTitle?: string; // 可选的自定义弹窗标题
}

interface TemplateSwiperProps {
  title: string;          // 主标题
  subtitle: string;       // 副标题
  fetchUrl: string;       // 数据接口 URL
  itemsPerPage?: number;  // 每页显示数量（可选，默认6）
  popupItems?: {          // 自定义弹窗选项（可选）
    icon: React.ReactNode;
    text: string;
    action?: () => void;
  }[];
}

const TemplateSwiper = ({
  title,
  subtitle,
  fetchUrl,
  itemsPerPage = 6,
  popupItems
}: TemplateSwiperProps) => {
  const [images, setImages] = useState<SwiperItem[]>([]);
  const [hoveredEllipsisId, setHoveredEllipsisId] = useState<number | null>(null);
  const [currentPage, setCurrentPage] = useState(0);
  const [showArrows, setShowArrows] = useState(false);
  const [hoveredItemId, setHoveredItemId] = useState<number | null>(null);
  const navigate = useNavigate()
  const totalPages = Math.ceil(images.length / itemsPerPage);
  const visibleImages = images.slice(
    currentPage * itemsPerPage,
    (currentPage + 1) * itemsPerPage
  );

  // 获取数据
  const fetchData = async () => {
    try {
      const res = await axios.get(fetchUrl);
      setImages(res.data);
    } catch (error) {
      console.error('数据获取失败:', error);
    }
  };

  useEffect(() => {
    fetchData();
  }, [fetchUrl]);

  // 翻页控制
  const handleNext = () => {
    if (currentPage < totalPages - 1) {
      setCurrentPage(prev => prev + 1);
    }
  };

  const handlePrev = () => {
    if (currentPage > 0) {
      setCurrentPage(prev => prev - 1);
    }
  };

  // 默认弹窗选项
  const defaultPopupItems = [
    { icon: <EyeOutlined />, text: '查看详情' },
    { icon: <StarOutlined />, text: '收藏' },
    { icon: <img src={search2} alt="找相似" style={{ width: '12px', height: '12px' }} />, text: '找相似' },
    { icon: <CalendarOutlined />, text: '新页签打开' },
    { icon: <ShareAltOutlined />, text: '分享' }
  ];

  const finalPopupItems = popupItems || defaultPopupItems;

  return (
    <div className="template-swiper">
      <div className="section-top">
        <h2>{title}</h2>
        <div className="notify">
          <p>{subtitle}</p>
          <p className="more">更多<span><RightOutlined /></span></p>
        </div>
      </div>

      <div
        className="swiper-section"
        onMouseEnter={() => setShowArrows(true)}
        onMouseLeave={() => setShowArrows(false)}
      >
        {showArrows && (
          <>
            {currentPage > 0 && (
              <div className="arrow left" onClick={handlePrev}>
                <LeftOutlined />
              </div>
            )}
            {currentPage < totalPages - 1 && (
              <div className="arrow right" onClick={handleNext}>
                <RightOutlined />
              </div>
            )}
          </>
        )}

        <div className="swiper-container">
          {visibleImages.map(item => (
            <div key={item.id} className="swiper-item" >
              <div
                className="image-container"
                onMouseEnter={() => setHoveredItemId(item.id)}
                onMouseLeave={() => setHoveredItemId(null)}
              >
                <img src={item.img} alt={title} onClick={() => {
                  navigate('/Createdesign');
                  recordRecentAccess(item, title); // 添加这行
                }}

                />
                <div className={`hover-elements ${hoveredItemId === item.id ? 'active' : ''}`}>
                  <div className="top-icons">
                    <div className="top-left">
                      <EyeOutlined className="swiperIcon" />
                      <StarOutlined className="swiperIcon" />
                    </div>
                    <EllipsisOutlined
                      className="swiperIcon"
                      onMouseEnter={() => setHoveredEllipsisId(item.id)}
                      onMouseLeave={() => setHoveredEllipsisId(null)}
                    />
                  </div>

                  <div className={`ellipsis-popup ${hoveredEllipsisId === item.id ? 'active' : ''}`}>
                    <h5>{item.popupTitle || `${title} ${item.id}`}</h5>
                    {finalPopupItems.map((popupItem, index) => (
                      <div
                        key={index}
                        className="popup-item"
                        onClick={popupItem.action}
                      >
                        {popupItem.icon} {popupItem.text}
                      </div>
                    ))}
                  </div>

                  <div className="bottom-content">
                    <Button className="use-btn" type="primary">
                      <img src={search} alt="找相似" style={{ width: '12px', height: '12px' }} />
                      找相似
                    </Button>
                    <CrownOutlined className="vip-icon" />
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default TemplateSwiper;